//
//  ZRLoginViewController.m
//  SinaByOC
//
//  Created by 张锐 on 16/2/28.
//  Copyright © 2016年 zhangr. All rights reserved.
//


#import "ZRLoginViewController.h"
#import <AFNetworking.h>
#import "ZRTokenModel.h"

@interface ZRLoginViewController ()<UIWebViewDelegate>

@property (nonatomic,strong) UIWebView * webView;

@end

@implementation ZRLoginViewController


static NSString* app_key = @"3932873718";

static NSString* app_secret = @"fca9228d86991e1970e7b02359ccb2d7";

static NSString* back_url = @"https://www.baidu.com";


//webView
-(void)loadView{

    self.webView = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
    self.webView.delegate = self;

    self.view = self.webView;

}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self loadWebView];
    
    [self setupNavButton];

    
}
/**
 *  加载网页登录界面
 */
-(void)loadWebView{

//    https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code
    
    NSString *URLString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@&response_type=code",app_key,back_url];
    
    NSURL * url = [NSURL URLWithString:URLString];
    
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    
    [self.webView loadRequest:request];

}

#pragma mark - NAV相关
-(void)setupNavButton{

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backButtonClick)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"自动填充" style:UIBarButtonItemStylePlain target:self action:@selector(fillUserIdAndPasswd)];

}
-(void)backButtonClick{

    //回跳控制器
    [self dismissViewControllerAnimated:YES completion:^{}];

}
//JS代码注入
-(void)fillUserIdAndPasswd{

    NSString * js = @"document.getElementById(\"userId\").value = \"15114604266\";document.getElementById(\"passwd\").value = \"lashinidie123\"";
    
    [self.webView stringByEvaluatingJavaScriptFromString:js];
    
}

#pragma mark - webView代理方法
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString * URLString = request.URL.absoluteString;
    
    if ([URLString hasPrefix:back_url]) {
        
        NSString *code = [[URLString componentsSeparatedByString:@"="] lastObject];
        
        [self getTokenByCode:code andSuccessBlock:^{
            
            NSLog(@"成功");
            
        } andFailureBlock:^{
            
            NSLog(@"失败");
            
        }];
    }
    return YES;
}
/**
 *  通过code获取Token
 *
 *  @param code code
 */
-(void)getTokenByCode:(NSString *)code andSuccessBlock:(void(^)())successBlock andFailureBlock:(void(^)())failureBlock{
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    /*
     必选	类型及范围	说明
     client_id	true	string	申请应用时分配的AppKey。
     client_secret	true	string	申请应用时分配的AppSecret。
     grant_type	true	string	请求的类型，填写authorization_code
     
     grant_type为authorization_code时
     必选	类型及范围	说明
     code	true	string	调用authorize获得的code值。
     redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
     */
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
    
    NSDictionary * parameters = @{@"client_id":app_key,
                                  @"client_secret":app_secret,
                                  @"grant_type":@"authorization_code",
                                  @"code":code,
                                  @"redirect_uri":back_url
                                  };
    
        [manager POST:@"https://api.weibo.com/oauth2/access_token" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           
            NSDictionary * tokenDic = (NSDictionary *)responseObject;
            
            ZRTokenModel * token = [ZRTokenModel tokenModelWithDictiorary:tokenDic];
            
            [self getUserInfoByToken:token andSuccessBlock:successBlock andFailureBlock:failureBlock];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failureBlock();
            NSLog(@"%@",error);
            
        }];  

}
/**
 *  通过TOKEN获取用户信息
 *
 *  @param token token
 */
-(void)getUserInfoByToken:(ZRTokenModel *)token andSuccessBlock:(void(^)())successBlock andFailureBlock:(void(^)())failureBlock{
    
    /*
     
     必选	类型及范围	说明
     access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
     uid	false	int64	需要查询的用户ID。
     screen_name	false	string	需要查询的用户昵称。
     */
    
    NSDictionary * parameters = @{
                                  @"access_token":token.access_token,
                                  @"uid":token.uid
                                  };

    [[AFHTTPSessionManager manager]GET:@"https://api.weibo.com/2/users/show.json" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *userInfo = (NSDictionary *)responseObject;
        
        token.screen_name = userInfo[@"screen_name"];
        
        token.profile_image_url = userInfo[@"profile_image_url"];
       
        [token saveWithFileName:@"userInfo.db"];
        
        successBlock();
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failureBlock();
        NSLog(@"%@",error);
    }];

}

@end
